<?php

namespace app\common\model;

use app\common\service\StatusService;
use think\Db;
use think\Model;


class Banner extends Model
{

    

    

    // 表名
    protected $name = 'banner';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'start_time_text',
        'end_time_text',
	    'position_text',
	    'jump_type_text'
    ];
	
	
	public function getPositionTextAttr($value, $data) {
		$value = $value ? :$data['position'];
		$list = StatusService::$bannerPositionList;
		return $list[$value] ? : '';
	}
	
	public function getJumpTypeTextAttr($value, $data) {
		$value = $value ? :$data['jump_type'];
		$list = StatusService::$bannerJumpTypeList;
		return $list[$value] ? : '';
	}

    public function getStartTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['start_time']) ? $data['start_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getEndTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['end_time']) ? $data['end_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }
	
	/**
	 * @param array $positions
	 * @return false|\PDOStatement|string|\think\Collection
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function getBannerByPositions(array $positions)
	{
		
		$where = [
			'position' => ['in', $positions],
			'start_time' => ['elt', time()],
			'end_time' => ['egt', time()]
		];
		
		$list = Db::name('banner')
			->where($where)
			->order(['sort' => 'ASC', 'id' => 'DESC'])
			->field('id, name, image, jump_type, params, position')
			->select();
		return $list;
	}
	
	protected function setStartTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setEndTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


}
